//
//  PageTabBar.swift
//  scfriend
//
//  Created by wulanzhou on 2017/7/27.
//  Copyright © 2017年 wulanzhou. All rights reserved.
//

import UIKit

class PageTabBar: UIView {

    private var currentIndex:Int = 0
    typealias PageTabBarSelectedItemIndexBlock = (_ index:Int) -> ()
    var tabBarSelectedItemIndexBlock:PageTabBarSelectedItemIndexBlock?
    
    private lazy var personButton:UIButton = {
        
        let btn:UIButton = UIButton.init(type: .custom)
        btn.frame = CGRect(x: self.width/2.0, y: 0, width: self.width/2.0, height: self.height)
        btn.setTitle("个人", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.tag = 101
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14.0)
        btn.addTarget(self, action: #selector(menuClick(sender:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var groupButton:UIButton = {
        
        let btn:UIButton = UIButton.init(type: .custom)
        btn.frame = CGRect(x: 0, y: 0, width: self.width/2.0, height: self.height)
        btn.setTitle("小组", for: .normal)
        btn.setTitleColor(UIColor.withRGBA(42, 173, 240), for: .normal)
        btn.backgroundColor = UIColor.white
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14.0)
        btn.tag = 100
        btn.addTarget(self, action: #selector(menuClick(sender:)), for: .touchUpInside)
        return btn
    }()
    
    @objc fileprivate func menuClick(sender:UIButton){
    
        self.tabBarSelectedItemIndexBlock?(sender.tag - 100)
        /**
        self.selectTab(index: sender.tag - 100, animate: true, completion:{ () in
           self.tabBarSelectedItemIndexBlock?(self.currentIndex)
        })
        **/
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.clipsToBounds = true
        self.backgroundColor = UIColor.clear
        self.layer.cornerRadius = 5.0
        self.layer.borderWidth = 0.5
        self.layer.borderColor = UIColor.white.cgColor
        self.layer.masksToBounds = true
        
        self.addSubview(self.groupButton)
        self.addSubview(self.personButton)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func selectTab(index:Int,animate:Bool,completion:(() -> Void)?) {
        
        if index != currentIndex {
        
            (self.viewWithTag(100 + index) as? UIButton)?.setTitleColor(UIColor.withRGBA(42, 173, 240), for: .normal)
            (self.viewWithTag(100 + index) as? UIButton)?.backgroundColor = UIColor.white
            (self.viewWithTag(100 + self.currentIndex) as? UIButton)?.setTitleColor(UIColor.white, for: .normal)
            (self.viewWithTag(100 + self.currentIndex) as? UIButton)?.backgroundColor = UIColor.clear
            currentIndex = index
            completion?()
        }
        
    }
    

}
